<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天机器人演示</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .chat-container {
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 10px;
            height: 400px;
            overflow-y: auto;
            margin-bottom: 10px;
            background-color: #f9f9f9;
        }
        .message {
            margin-bottom: 10px;
            padding: 8px 15px;
            border-radius: 18px;
            max-width: 90%;
            word-wrap: break-word;
            line-height: 1.5;
            font-size: 15px;
        }
        .user-message {
            background-color: #dcf8c6;
            margin-left: auto;
            text-align: right;
        }
        .assistant-message {
            background-color: #e6f7ff;
            color: #000000;
            align-self: flex-start;
            margin-top: 10px;
        }
        .assistant-message h1, .assistant-message h2, .assistant-message h3 {
            margin-top: 10px;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }
        .assistant-message h1 {
            font-size: 1.5em;
            border-bottom: 1px solid #eee;
            padding-bottom: 5px;
        }
        .assistant-message h2 {
            font-size: 1.3em;
        }
        .assistant-message h3 {
            font-size: 1.1em;
        }
        .assistant-message ul, .assistant-message ol {
            margin-left: 20px;
            margin-bottom: 10px;
        }
        .assistant-message li {
            margin-bottom: 5px;
        }
        .assistant-message p {
            margin-bottom: 10px;
        }
        .assistant-message code {
            background-color: #f4f4f4;
            padding: 2px 4px;
            border-radius: 3px;
            font-family: monospace;
            font-size: 0.9em;
        }
        .assistant-message pre {
            background-color: #f4f4f4;
            padding: 10px;
            border-radius: 5px;
            overflow-x: auto;
            margin: 10px 0;
        }
        .assistant-message strong {
            font-weight: bold;
        }
        .assistant-message em {
            font-style: italic;
        }
        .assistant-message blockquote {
            border-left: 3px solid #ccc;
            padding-left: 10px;
            color: #666;
            margin: 10px 0;
        }
        .reasoning-message {
            background-color: #f1f1f1;
            margin-right: auto;
            font-style: italic;
            color: #666;
            padding: 10px;
            border-radius: 8px;
            border-left: 3px solid #999;
            margin-bottom: 10px;
            font-size: 14px;
            white-space: pre-wrap;
            word-break: break-word;
            overflow-wrap: break-word;
            display: block;
        }
        .input-area {
            display: flex;
            margin-top: 10px;
        }
        #message-input {
            flex-grow: 1;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-right: 10px;
        }
        .button {
            padding: 10px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .button:hover {
            background-color: #45a049;
        }
        .button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        input:disabled {
            background-color: #f5f5f5;
            cursor: not-allowed;
        }
        .typing-indicator {
            color: #999;
            font-style: italic;
            margin-bottom: 10px;
            display: none;
        }
        .controls {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        .privacy-alert {
            background-color: #fff3cd;
            border: 1px solid #ffeeba;
            border-radius: 5px;
            padding: 10px 15px;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            color: #856404;
        }
        .alert-icon {
            font-size: 20px;
            margin-right: 10px;
        }
        .alert-content {
            flex: 1;
            font-size: 14px;
            line-height: 1.4;
        }
        .message-group {
            border-left: 2px solid #ddd;
            padding-left: 10px;
            margin-bottom: 20px;
        }
        .message-group .reasoning-message:not(:last-child) {
            margin-bottom: 5px;
        }
        .message-group .assistant-message {
            margin-top: 10px;
        }
        .reasoning-container {
            margin-top: 5px;
            margin-bottom: 10px;
        }
        .reasoning-toggle {
            background-color: #e0e0e0;
            border: none;
            border-radius: 3px;
            padding: 3px 8px;
            font-size: 12px;
            cursor: pointer;
            margin-bottom: 5px;
            color: #555;
        }
        .reasoning-toggle:hover {
            background-color: #d0d0d0;
        }
        .reasoning-content {
            background-color: #f5f5f5;
            border-radius: 5px;
            padding: 10px;
            font-size: 14px;
            color: #666;
            white-space: pre-line;
            display: none;
            margin-bottom: 5px;
            border-left: 3px solid #999;
        }
        .copy-button {
            position: absolute;
            top: 5px;
            right: 5px;
            background-color: #f1f1f1;
            border: none;
            border-radius: 3px;
            padding: 3px 8px;
            font-size: 12px;
            cursor: pointer;
            opacity: 0;
            transition: opacity 0.2s ease;
        }
        .assistant-message:hover .copy-button {
            opacity: 1;
        }
        .copy-button:hover {
            background-color: #e0e0e0;
        }
        .copy-success {
            background-color: #4CAF50 !important;
            color: white;
        }
        /* 用户选择器样式 */
        .user-selector {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .user-select {
            padding: 8px;
            border-radius: 5px;
            border: 1px solid #ccc;
            min-width: 120px;
        }
        .add-user-btn {
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            padding: 8px;
            cursor: pointer;
        }
        .add-user-btn:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
    <h1>聊天机器人演示</h1>
    
    <div class="privacy-alert">
        <i class="alert-icon">⚠️</i>
        <div class="alert-content">
            <strong>隐私提示：</strong>与AI的对话仅临时存储在内存中，不会永久保存到数据库。本应用使用百炼平台的deepseek模型，请注意保护您的隐私信息。清除对话后，历史记录将无法恢复。
        </div>
    </div>
    
    <div class="controls">
        <div class="user-selector">
            <label for="user-select">用户:</label>
            <select id="user-select" class="user-select" onchange="switchUser()">
                <option value="user1">用户1</option>
                <option value="user2">用户2</option>
                <option value="user3">用户3</option>
            </select>
            <button class="add-user-btn" onclick="addNewUser()">添加用户</button>
        </div>
        <button id="clear-button" onclick="clearHistory()" class="button" style="background-color: #f44336;">清除历史</button>
    </div>
    <div class="chat-container" id="chat-container"></div>
    <div class="typing-indicator" id="typing-indicator">AI思考中...</div>
    <div class="input-area">
        <input type="text" id="message-input" placeholder="输入您的消息..." onkeydown="if(event.key==='Enter' && !isProcessing) sendMessage()">
        <button id="send-button" onclick="sendMessage()" class="button">发送</button>
    </div>

    <script>
        // 标记是否正在处理消息
        let isProcessing = false;
        // 用户列表
        let userList = ['user1', 'user2', 'user3'];
        
        // 设置输入状态（启用/禁用）
        function setInputState(disabled) {
            document.getElementById('message-input').disabled = disabled;
            document.getElementById('send-button').disabled = disabled;
            document.getElementById('user-select').disabled = disabled;
            document.getElementById('clear-button').disabled = disabled;
            
            // 视觉反馈
            if (disabled) {
                document.getElementById('send-button').style.opacity = '0.5';
                document.getElementById('send-button').style.cursor = 'not-allowed';
                document.getElementById('clear-button').style.opacity = '0.5';
                document.getElementById('clear-button').style.cursor = 'not-allowed';
            } else {
                document.getElementById('send-button').style.opacity = '1';
                document.getElementById('send-button').style.cursor = 'pointer';
                document.getElementById('clear-button').style.opacity = '1';
                document.getElementById('clear-button').style.cursor = 'pointer';
            }
            
            isProcessing = disabled;
        }
        
        // 获取用户ID
        function getUserId() {
            return document.getElementById('user-select').value || 'user1';
        }
        
        // 切换用户
        function switchUser() {
            if (isProcessing) {
                alert('AI正在回复，请等待完成后再切换用户');
                // 还原选择框到之前的值
                const userSelect = document.getElementById('user-select');
                const prevIndex = Array.from(userSelect.options).findIndex(opt => opt.selected);
                userSelect.selectedIndex = prevIndex;
                return;
            }
            
            // 保存选择的用户ID到localStorage
            const userId = getUserId();
            localStorage.setItem('selectedUserId', userId);
            
            // 加载聊天历史
            loadChatHistory();
            
            // 检查系统消息并初始化
            initializeSystemMessage(userId);
        }
        
        // 初始化系统消息
        function initializeSystemMessage(userId) {
            fetch(`/api/ai/history?userId=${userId}`)
                .then(response => response.json())
                .then(history => {
                    // 检查历史记录中是否已有系统消息
                    const hasSystemMessage = history.some(msg => msg.role.toUpperCase() === 'SYSTEM');
                    
                    if (!hasSystemMessage) {
                        console.log('未检测到系统消息，正在初始化...');
                        // 如果没有系统消息，初始化默认系统消息
                        fetch(`/api/ai/init-system?userId=${userId}`, {
                            method: 'POST'
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                console.log('系统消息已初始化:', data.systemMessage);
                                // 重新加载聊天历史以显示系统消息
                                loadChatHistory();
                            } else {
                                console.error('初始化系统消息失败:', data.error);
                            }
                        })
                        .catch(error => console.error('初始化系统消息出错:', error));
                    }
                })
                .catch(error => console.error('检查系统消息失败:', error));
        }
        
        // 添加新用户
        function addNewUser() {
            if (isProcessing) {
                alert('AI正在回复，请等待完成后再添加用户');
                return;
            }
            
            const newUserId = prompt('请输入新用户ID（英文字母和数字）:');
            if (!newUserId) return;
            
            // 验证用户ID格式
            if (!/^[a-zA-Z0-9_-]+$/.test(newUserId)) {
                alert('用户ID只能包含英文字母、数字、下划线和连字符');
                return;
            }
            
            // 检查是否已存在
            if (userList.includes(newUserId)) {
                alert('该用户ID已存在');
                return;
            }
            
            // 添加到用户列表和下拉框
            userList.push(newUserId);
            const userSelect = document.getElementById('user-select');
            const option = document.createElement('option');
            option.value = newUserId;
            option.textContent = newUserId;
            userSelect.appendChild(option);
            
            // 选择新添加的用户
            userSelect.value = newUserId;
            
            // 保存选择的用户ID到localStorage
            localStorage.setItem('selectedUserId', newUserId);
            
            // 加载该用户的聊天历史（可能为空）
            loadChatHistory();
            
            // 初始化系统消息
            initializeSystemMessage(newUserId);
        }
        
        // 加载历史消息
        function loadChatHistory() {
            const userId = getUserId();
            fetch(`/api/ai/history?userId=${userId}`)
                .then(response => response.json())
                .then(history => {
                    const chatContainer = document.getElementById('chat-container');
                    chatContainer.innerHTML = '';
                    
                    let currentUserMessage = null;
                    let currentMessageGroup = null;
                    
                    history.forEach(msg => {
                        const isUser = msg.role.toUpperCase() === 'USER';
                        
                        if (isUser) {
                            // 用户消息直接添加到对话容器
                            const messageDiv = document.createElement('div');
                            messageDiv.className = 'message user-message';
                            messageDiv.textContent = msg.content;
                            chatContainer.appendChild(messageDiv);
                            
                            // 为接下来的助手回复创建新的消息组
                            currentMessageGroup = document.createElement('div');
                            currentMessageGroup.className = 'message-group';
                            chatContainer.appendChild(currentMessageGroup);
                        } else {
                            // 助手消息添加到当前消息组
                            if (currentMessageGroup) {
                                // 添加回复内容
                                const messageDiv = document.createElement('div');
                                messageDiv.className = 'message assistant-message';
                                addFormattedResponse(messageDiv, msg.content);
                                
                                // 如果存在推理内容，则添加推理过程
                                if (msg.reasoningContent) {
                                    const reasoningDiv = document.createElement('div');
                                    reasoningDiv.className = 'message reasoning-message';
                                    reasoningDiv.textContent = msg.reasoningContent;
                                    currentMessageGroup.appendChild(reasoningDiv);
                                }
                                
                                currentMessageGroup.appendChild(messageDiv);
                            }
                        }
                    });
                    
                    chatContainer.scrollTop = chatContainer.scrollHeight;
                })
                .catch(error => console.error('加载历史消息失败:', error));
        }
        
        // 发送消息 (使用流式API)
        function sendMessage() {
            // 检查是否已在处理中
            if (isProcessing) {
                return;
            }
            
            const messageInput = document.getElementById('message-input');
            const message = messageInput.value.trim();
            const userId = getUserId();
            
            if (!message) return;
            
            // 禁用输入框和按钮
            setInputState(true);
            
            // 添加用户消息到界面
            addMessageToUI(message, true);
            messageInput.value = '';
            
            // 显示正在输入指示器
            document.getElementById('typing-indicator').style.display = 'block';
            
            // 创建消息组容器，包含本次对话的思考过程和回复
            const messageGroupDiv = document.createElement('div');
            messageGroupDiv.className = 'message-group';
            document.getElementById('chat-container').appendChild(messageGroupDiv);
            
            // 使用流式API
            const token = localStorage.getItem('token') || '';
            const url = `/api/ai/stream?userId=${userId}&content=${encodeURIComponent(message)}&token=${token}`;
            const eventSource = new EventSource(url);
            
            let reasoningContent = '';
            let responseContent = '';
            let currentReasoningDiv = null;
            let currentResponseDiv = null;
            
            eventSource.addEventListener('reasoning', function(event) {
                reasoningContent += event.data;
                
                // 将思考过程添加到当前消息组
                if (!currentReasoningDiv) {
                    currentReasoningDiv = document.createElement('div');
                    currentReasoningDiv.className = 'message reasoning-message';
                    messageGroupDiv.appendChild(currentReasoningDiv);
                }
                
                currentReasoningDiv.textContent = reasoningContent;
                document.getElementById('chat-container').scrollTop = document.getElementById('chat-container').scrollHeight;
            });
            
            eventSource.addEventListener('content', function(event) {
                responseContent += event.data;
                
                // 将回复内容添加到当前消息组
                if (!currentResponseDiv) {
                    currentResponseDiv = document.createElement('div');
                    currentResponseDiv.className = 'message assistant-message';
                    messageGroupDiv.appendChild(currentResponseDiv);
                }
                
                // 使用格式化函数来设置内容
                addFormattedResponse(currentResponseDiv, responseContent);
                document.getElementById('chat-container').scrollTop = document.getElementById('chat-container').scrollHeight;
            });
            
            eventSource.addEventListener('error', function(event) {
                console.error('错误:', event.data);
                document.getElementById('typing-indicator').style.display = 'none';
                eventSource.close();
                // 出错时也要启用输入框和按钮
                setInputState(false);
            });
            
            eventSource.addEventListener('complete', function(event) {
                document.getElementById('typing-indicator').style.display = 'none';
                eventSource.close();
                // 启用输入框和按钮
                setInputState(false);
            });
            
            eventSource.onerror = function() {
                document.getElementById('typing-indicator').style.display = 'none';
                eventSource.close();
                // 出错时也要启用输入框和按钮
                setInputState(false);
            };
        }
        
        // 将消息添加到UI
        function addMessageToUI(message, isUser, isIncremental = false) {
            const chatContainer = document.getElementById('chat-container');
            
            if (isIncremental && !isUser) {
                const lastMessage = chatContainer.lastElementChild;
                if (lastMessage && lastMessage.classList.contains('assistant-message')) {
                    lastMessage.textContent += message;
                } else {
                    const messageDiv = document.createElement('div');
                    messageDiv.className = 'message assistant-message';
                    messageDiv.textContent = message;
                    chatContainer.appendChild(messageDiv);
                }
            } else {
                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${isUser ? 'user-message' : 'assistant-message'}`;
                messageDiv.textContent = message;
                chatContainer.appendChild(messageDiv);
            }
            
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
        
        // 清除历史
        function clearHistory() {
            // 如果AI正在回复，不允许清除
            if (isProcessing) {
                alert('AI正在回复，请等待完成后再清除历史');
                return;
            }
            
            const userId = getUserId();
            fetch(`/api/ai/history?userId=${userId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('chat-container').innerHTML = '';
                    alert('聊天历史已清除');
                    
                    // 初始化系统消息
                    initializeSystemMessage(userId);
                }
            })
            .catch(error => console.error('清除历史失败:', error));
        }
        
        // 将回复内容添加到当前消息组，支持基本markdown格式
        function addFormattedResponse(element, text) {
            // 首先处理可能存在的原始HTML标签，进行转义
            text = text.replace(/&/g, '&amp;')
                       .replace(/</g, '&lt;')
                       .replace(/>/g, '&gt;')
                       .replace(/"/g, '&quot;')
                       .replace(/'/g, '&#039;');
            
            // 然后进行Markdown处理
            
            // 处理标题
            text = text.replace(/^### (.*?)$/gm, '<h3>$1</h3>');
            text = text.replace(/^## (.*?)$/gm, '<h2>$1</h2>');
            text = text.replace(/^# (.*?)$/gm, '<h1>$1</h1>');
            
            // 处理粗体和斜体
            text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
            text = text.replace(/\*(.*?)\*/g, '<em>$1</em>');
            
            // 处理列表
            text = text.replace(/^\- (.*?)$/gm, '<li>$1</li>').replace(/<li>(.*?)<\/li>(?!\n<li>)/gs, '<ul><li>$1</li></ul>');
            text = text.replace(/^\d+\. (.*?)$/gm, '<li>$1</li>').replace(/<li>(.*?)<\/li>(?!\n<li>)/gs, '<ol><li>$1</li></ol>');
            
            // 处理代码块
            text = text.replace(/```(.*?)```/gs, '<pre><code>$1</code></pre>');
            
            // 处理行内代码
            text = text.replace(/`(.*?)`/g, '<code>$1</code>');
            
            // 处理引用
            text = text.replace(/^> (.*?)$/gm, '<blockquote>$1</blockquote>');
            
            // 处理段落
            text = text.replace(/(?<!\n)\n(?!\n)/g, '<br>');
            text = text.replace(/\n\n/g, '</p><p>');
            
            // 设置HTML内容
            element.innerHTML = '<p>' + text + '</p>';
            
            // 添加复制按钮
            addCopyButton(element, element.textContent || text);
        }

        // 添加复制功能
        function addCopyButton(element, text) {
            const copyButton = document.createElement('button');
            copyButton.className = 'copy-button';
            copyButton.textContent = '复制';
            copyButton.onclick = function(e) {
                e.stopPropagation(); // 防止冒泡
                
                // 创建一个临时textarea元素来复制文本
                const textarea = document.createElement('textarea');
                textarea.value = text;
                textarea.style.position = 'fixed'; // 避免影响页面布局
                document.body.appendChild(textarea);
                textarea.select();
                
                try {
                    // 尝试复制
                    document.execCommand('copy');
                    // 显示复制成功反馈
                    copyButton.textContent = '已复制!';
                    copyButton.classList.add('copy-success');
                    
                    // 2秒后恢复按钮原状
                    setTimeout(function() {
                        copyButton.textContent = '复制';
                        copyButton.classList.remove('copy-success');
                    }, 2000);
                } catch (err) {
                    console.error('复制失败:', err);
                }
                
                // 移除临时元素
                document.body.removeChild(textarea);
            };
            
            element.appendChild(copyButton);
        }
        
        // 页面加载时加载历史消息
        window.onload = function() {
            // 恢复上次选择的用户
            const lastUserId = localStorage.getItem('selectedUserId');
            if (lastUserId) {
                const userSelect = document.getElementById('user-select');
                // 检查该用户是否存在于下拉列表中
                const exists = Array.from(userSelect.options).some(opt => opt.value === lastUserId);
                
                if (!exists) {
                    // 如果不存在，添加该用户
                    userList.push(lastUserId);
                    const option = document.createElement('option');
                    option.value = lastUserId;
                    option.textContent = lastUserId;
                    userSelect.appendChild(option);
                }
                
                // 选择该用户
                userSelect.value = lastUserId;
            }
            
            // 获取当前用户ID
            const userId = getUserId();
            
            // 加载聊天历史
            loadChatHistory();
            
            // 初始化系统消息
            initializeSystemMessage(userId);
        };
    </script>
</body>
</html> 